Vue.component('chart', {
	model: {
		prop: 'data',
		event: 'change'
	},
	props: [],
	template : "<div style='width:100%;'></div>",
	mounted: function() {
		//这里可以操作数据了
		var chart = LightweightCharts.createChart(this.$el, { width: this.$el.clientWidth-20, height: 420 });
		chart.applyOptions({
			localization: {
				dateFormat: 'yy/MM/dd',
				timeFormatter: function (timestamp) {
					return new Date(timestamp*1000).toISOString();
				},
			},
			handleScroll: {
				mouseWheel : false,
			},
		});

		var candlestickSeries = chart.addCandlestickSeries({
			upColor: '#ef5350',
			downColor: '#26a69a',
			wickUpColor: '#ef5350',
			wickDownColor: '#26a69a',
			borderVisible: false,
			scaleMargins: {
				top: 0,
				bottom: 0.8,
			},
		});

		var data = [];
		for (var i = 0; i < this.$attrs.data.data.length; i++) {
			var e = this.$attrs.data.data[i];
			data.push({
				time : Math.round((new Date(e.time)).valueOf()/1000),
				open : e.open,
				close : e.close,
				high : e.high,
				low : e.low,
			})
		}
		candlestickSeries.setData(data);

		function getLineData(data, key) {
			var out = [];
			for (var i = 0; i < data.length; i++) {
				var e = data[i];
				out.push({
					time : Math.round((new Date(e.time)).valueOf()/1000),
					value : e[key]
				})
			}
			return out;
		}
		/*
        var histogramSeries = chart.addHistogramSeries({
            base: 0,
            scaleMargins: {
                top: 0.8,
                bottom: 1,
            }
        });
        histogramSeries.setData(getLineData(this.$attrs.data.data, "turnover"));
        */
		/*
        const color = ['#0099CC','#FFCC99', '#CCCCFF', '#FFCC00'];
        for (var i = 0; i < this.$attrs.data.key.length; i++) {
            var lineSeries = chart.addLineSeries({
                color: color[i % color.length],
                crosshairMarkerVisible: false,
                lineWidth: 1,
                scaleMargins: {
                    top: 0,
                    bottom: 0.8,
                },
            });
            lineSeries.setData(getLineData(this.$attrs.data.data, this.$attrs.data.key[i]));
        }
        */
	}
});

Vue.component('parallel', {
	props: ["value", "column", "dimension"],
	template : "<div style='width:100%;height:500px;'></div>",
	mounted: function() {
		var chart = echarts.init(this.$el);
		var my = this;
		chart.on('axisareaselected', function () {
			var series = chart.getModel().getSeries();
			for (var i = 0; i < series.length; i++) {
				var index = series[i].getRawIndicesByActiveState('active');
				var select = [];
				for (var i in index) {
					select.push(my.raw[index[i]]);
				}
				console.log('axisareaselected', index, select, series[i]);
				my.$emit('update:selected', index);
			}
		});
		var option = {
			visualMap: {
				show: true,
				min: -10,
				max: 10,
				realtime: false,
				dimension: this.column.indexOf(this.dimension),
				inRange: {
					//color: ['#d94e5d','#eac736','#50a3ba'].reverse(),
                    //color : ['#71ae46','#ebe12a','#ce2626']
					color : ["#00AF64", "#FFD300", "#E40045"]
					//color : ["#4671D5", "#FFFF40", "#FF4040"]
					//color: ['#ff0000','#ffff00','#0000ff'].reverse(),#00CC00, #FFD300, #FF0000
				},
			},
			parallelAxis: [],
			series: {
				type: 'parallel',
				lineStyle: {
					width: 1
				},
				data: []
			}
		};
		this.update = function() {
			chart.clear();
			if (null != this.column) {
				option.visualMap.dimension = this.column.indexOf(this.dimension);
			}
			function setOption(arr, key) {
				option.parallelAxis = [];
				for (var j = 0; j < key.length; j++) {
					option.parallelAxis.push({
						dim : j,
						name: COLUMN_NAME[key[j]] || key[j],
						splitNumber: 20
					});
				}

				option.series.data = [];
				var max = Number.MIN_VALUE;
				var min = Number.MAX_VALUE;
				for (var i = 0; i < arr.length; i++) {
					var e = arr[i];
					var row = [];
					if (!e) {
						option.series.data.push(row);
						continue;
					}
					for (var j = 0; j < key.length; j++) {
						try {
						    var data = e[key[j]]||0;
						    if (option.visualMap.dimension == j) {
						        if (data > max) {
						            max = data;
                                }
						        if (data < min) {
						            min = data;
                                }
                            }
							row.push(data);
						} catch (err) {
							console.log("parallel data error", [err, arr, i, e, key, j]);
						}
					}
					option.series.data.push(row);
				}
                option.visualMap.max = max;
                option.visualMap.min = min;
			}
			setOption(this.raw, this.column);
			chart.setOption(option);
		};
	},
	data: function () {
		return {
			raw : []
		}
	},
	watch : {
		column : function (val) {
			this.update();
		},
		value : function (val) {
			this.raw = val.slice();
			this.update();
		},
		dimension : function (val) {
			this.update();
		},
	}
});

Vue.component('stock-chart', {
	props: ["value", "column"],
	template : "<div style='width:100%;height:480px;'></div>",
	mounted: function() {
		var chart = echarts.init(this.$el);

		function variance(day) {
			var i = 0;
			var diff = new Array(day.length);

			for (i = 20; i < day.length; i++){
				var avg = 0;
				for (var j = 0; j < 20; j++) {
					var e = day[i-j];
					avg += e.high + e.low;
				}
				avg = avg / 40;

				var s = 0;
				for (var j = 0; j < 20; j++) {
					var e = day[i-j];
					s += (e.high-avg)*(e.high-avg) + (e.low-avg)*(e.low-avg);
				}
				s = Math.sqrt(s / 39);

				diff[i] = {avg:avg,sv:s};
			}

			if (day.length >= 20) {
				for (i = 0; i < 20; i++) {
					diff[i] = diff[20];
				}
			}

			return diff;
		}

		var colorList = ['#c23531','#2f4554', '#61a0a8', '#d48265', '#91c7ae','#749f83',  '#ca8622', '#bda29a','#6e7074', '#546570', '#c4ccd3'];
		var labelFont = 'bold 12px Sans-serif';

		var dates = [];
		var data = [];
		var volumes = [];
		var dataMA5 = [];
		var dataMA10 = [];
		var dataMA30 = [];
		var dataHigh = [];
		var dataLow = [];

		var stock = {
			day : this.value.data
		};
    	// [open, close, lowest, highest] （即：[开盘值, 收盘值, 最低值, 最高值]）
		var v = variance(stock.day);
		//console.log(v, stock.day);
		for (var i = 0; i < stock.day.length; i++){
			var e = stock.day[i];

			dates.push(e.time);
			data.push([e.open, e.close, e.low, e.high]);

			volumes.push(e.volume || null);
			dataMA5.push(e.ma_price5 || null);
			dataMA10.push(e.ma_price10 || null);

			var sv = v[i];
			dataMA30.push(sv.avg);
			dataHigh.push(sv.avg + (2 * sv.sv));
			dataLow.push(sv.avg - (2 * sv.sv));
		}

		option = {
			animation: false,
			color: colorList,
			axisPointer: {
				link: [{
					xAxisIndex: [0, 1]
				}]
			},
			dataZoom: [{
				type: 'slider',
				xAxisIndex: [0, 1],
				realtime: false,
				startValue: 0,
				endValue : stock.day.length - 1,
				top: 10,
				height: 20,
				//handleIcon: 'M10.7,11.9H9.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4h1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
				handleSize: '120%'
			}],
			xAxis: [{
				type: 'category',
				data: dates,
				boundaryGap : false,
				axisLine: { lineStyle: { color: '#777' } },
				axisLabel: {
					formatter: function (value) {
						return echarts.format.formatTime('MM-dd', value);
					}
				},
				min: 'dataMin',
				max: 'dataMax',
				axisPointer: {
					show: true
				}
			}, {
				type: 'category',
				gridIndex: 1,
				data: dates,
				scale: true,
				boundaryGap : false,
				splitLine: {show: false},
				axisLabel: {show: false},
				axisTick: {show: false},
				axisLine: { lineStyle: { color: '#777' } },
				splitNumber: 20,
				min: 'dataMin',
				max: 'dataMax',
				axisPointer: {
					type: 'shadow',
					label: {show: false},
					triggerTooltip: true,
					handle: {
						show: true,
						margin: 30,
						color: '#B80C00'
					}
				}
			}],
			yAxis: [{
				scale: true,
				splitNumber: 2,
				axisLine: { lineStyle: { color: '#777' } },
				splitLine: { show: true },
				axisTick: { show: false },
				axisLabel: {
					inside: true,
					formatter: '{value}\n'
				}
			}, {
				scale: true,
				gridIndex: 1,
				splitNumber: 2,
				axisLabel: {show: false},
				axisLine: {show: false},
				axisTick: {show: false},
				splitLine: {show: false}
			}],
			grid: [{
				left: 10,
				right: 10,
				top: 50,
				height: 180
			}, {
				left: 10,
				right: 10,
				height: 80,
				top: 260
			}],
			graphic: [{
				type: 'group',
				left: 'center',
				top: 35,
				width: 300,
				bounding: 'raw',
				children: [{
					id: 'MA5',
					type: 'text',
					style: {fill: colorList[1], font: labelFont},
					left: 0
				}, {
					id: 'MA10',
					type: 'text',
					style: {fill: colorList[2], font: labelFont},
					left: 'center'
				}, {
					id: 'MA30',
					type: 'text',
					style: {fill: colorList[3], font: labelFont},
					right: 0
				}, {
					id: 'High',
					type: 'text',
					style: {fill: colorList[4], font: labelFont},
					left: 'center'
				}, {
					id: 'Low',
					type: 'text',
					style: {fill: colorList[5], font: labelFont},
					right: 0
				}]
			}],
			series: [{
				name: 'Volume',
				type: 'bar',
				barWidth: '80%',
				xAxisIndex: 1,
				yAxisIndex: 1,
				itemStyle: {
					normal: {
						color: '#7fbe9e'
					},
					emphasis: {
						color: '#140'
					}
				},
				data: volumes
			}, {
				type: 'candlestick',
				name: '日K',
				barWidth: '80%',
				data: data,
				itemStyle: {
					normal: {
						color: '#ef232a',
						color0: '#14b143',
						borderColor: '#ef232a',
						borderColor0: '#14b143'
					},
					emphasis: {
						color: 'black',
						color0: '#444',
						borderColor: 'black',
						borderColor0: '#444'
					}
				}
			}, {
				name: 'MA30',
				type: 'line',
				data: dataMA30,
				smooth: true,
				showSymbol: false,
				lineStyle: {
					normal: {
						width: 1,
						color: '#FFD700'
					}
				}
			}, {
				name: 'High',
				type: 'line',
				data: dataHigh,
				smooth: true,
				showSymbol: false,
				lineStyle: {
					normal: {
						width: 1,
						color: '#FF4500'
					}
				}
			}, {
				name: 'Low',
				type: 'line',
				data: dataLow,
				smooth: true,
				showSymbol: false,
				lineStyle: {
					normal: {
						width: 1,
						color: '#7CFC00'
					},

				}
			}]
		};
		chart.setOption(option);
	},
	watch : {
		column : function (val) {
		},
		value : function (val) {
		},
		dimension : function (val) {
		},
	}
});